<template>
  <div class="virtual-play-page">
    <header class="header">
      <div class="header-content">
        <button class="back-btn" @click="$router.push('/back')">
          <span>‹</span>
          返回
        </button>
        <h1>虚拟歌单</h1>
      </div>
    </header>
    
    <div class="content">
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else class="playlist-container">
        <div class="playlist-list">
          <div 
            v-for="item in virtualPlayList" 
            :key="item.id" 
            class="playlist-item"
          >
            <div class="item-left">
              <div 
                class="checkbox" 
                :class="{ checked: !item.status }"
                @click="toggleStatus(item)"
              >
                <div class="checkmark" v-if="!item.status">✓</div>
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-condition">
                  {{ item.id }}.{{ item.left }} {{ item.opr }} {{ item.right }}
                </div>
              </div>
            </div>
            
            <div class="item-actions">
              <button class="more-btn" @click="openActionMenu(item, $event)">
                <span>⋯</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作菜单 -->
    <div v-if="showActionMenu" class="action-menu-overlay" @click="closeActionMenu">
      <div class="action-menu" :style="menuStyle" @click.stop>
        <button class="action-menu-item" @click="openEditForm(currentItem)">
          <span class="action-icon">✏️</span>
          编辑
        </button>
        <button class="action-menu-item delete" @click="confirmDelete(currentItem)">
          <span class="action-icon">🗑️</span>
          删除
        </button>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="closeDeleteConfirm">
      <div class="modal-content confirm-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
        </div>
        <div class="confirm-content">
          <p>是否删除虚拟歌单 "{{ currentItem?.name }}"？</p>
        </div>
        <div class="form-actions">
          <button class="btn btn-cancel" @click="closeDeleteConfirm">取消</button>
          <button class="btn btn-danger" @click="deleteVirtualPlay">确认删除</button>
        </div>
      </div>
    </div>

    <!-- 编辑表单弹窗 -->
    <div v-if="showEditForm" class="modal-overlay" @click="closeEditForm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>编辑虚拟歌单</h3>
          <button class="close-btn" @click="closeEditForm">×</button>
        </div>
        
        <div class="form">
          <div class="form-group">
            <label>名称</label>
            <input v-model="editForm.name" type="text" class="form-input">
          </div>
          
          <div class="form-group">
            <label>左值</label>
            <input v-model="editForm.left" type="text" class="form-input">
          </div>
          
          <div class="form-group">
            <label>操作符</label>
            <select v-model="editForm.opr" class="form-select">
              <option value="and">and</option>
              <option value="or">or</option>
              <option value="sub">sub</option>
              <option value="like">like</option>
            </select>
          </div>
          
          <div class="form-group">
            <label>右值</label>
            <input v-model="editForm.right" type="text" class="form-input">
          </div>
          
          <div class="form-actions">
            <button class="btn btn-cancel" @click="closeEditForm">取消</button>
            <button class="btn btn-confirm" @click="confirmEdit">确认</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增表单弹窗 -->
    <div v-if="showAddForm" class="modal-overlay" @click="closeAddForm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>新增虚拟歌单</h3>
          <button class="close-btn" @click="closeAddForm">×</button>
        </div>
        
        <div class="form">
          <div class="form-group">
            <label>名称</label>
            <input v-model="addForm.name" type="text" class="form-input" placeholder="请输入名称">
          </div>
          
          <div class="form-group">
            <label>左值</label>
            <input v-model="addForm.left" type="text" class="form-input" placeholder="请输入左值">
          </div>
          
          <div class="form-group">
            <label>操作符</label>
            <select v-model="addForm.opr" class="form-select">
              <option value="and">and</option>
              <option value="or">or</option>
              <option value="sub">sub</option>
              <option value="like">like</option>
            </select>
          </div>
          
          <div class="form-group">
            <label>右值</label>
            <input v-model="addForm.right" type="text" class="form-input" placeholder="请输入右值">
          </div>
          
          <div class="form-actions">
            <button class="btn btn-cancel" @click="closeAddForm">取消</button>
            <button class="btn btn-confirm" @click="confirmAdd">确认</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 悬浮添加按钮 -->
    <button 
      class="floating-add-btn"
      :style="floatingBtnStyle"
      @click="handleButtonClick"
      @mousedown="startDrag"
      @touchstart="handleTouchStart"
      @touchend="handleTouchEnd"
    >
      <span>+</span>
    </button>
  </div>
</template>

<script>
import { apiService } from '../utils/http'
import { tools } from '../utils/tools'

export default {
  name: 'VirtualPlay',
  data() {
    return {
      virtualPlayList: [],
      loading: true,
      showEditForm: false,
      showAddForm: false,
      showActionMenu: false,
      showDeleteConfirm: false,
      currentItem: null,
      menuStyle: {},
      editForm: {
        id: '',
        name: '',
        left: '',
        opr: 'and',
        right: ''
      },
      addForm: {
        name: '',
        left: '',
        opr: 'and',
        right: ''
      },
      // 拖拽相关数据
      isDragging: false,
      dragOffset: { x: 0, y: 0 },
      floatingBtnPosition: {
        x: 20, // 距离右侧的初始位置
        y: 30  // 距离底部的初始位置
      },
      // 触摸相关数据
      touchStartTime: 0,
      touchTimer: null,
      isTouchMoving: false
    }
  },
  computed: {
    floatingBtnStyle() {
      return {
        right: `${this.floatingBtnPosition.x}px`,
        bottom: `${this.floatingBtnPosition.y}px`,
        cursor: this.isDragging ? 'grabbing' : 'grab',
        transform: this.isDragging ? 'scale(1.1)' : 'scale(1)'
      }
    }
  },
  async mounted() {
    await this.queryVirtualPlayList()
    // 加载保存的位置
    this.loadFloatingBtnPosition()
  },
  beforeUnmount() {
    // 清理定时器
    if (this.touchTimer) {
      clearTimeout(this.touchTimer)
    }
  },
  methods: {
    // 加载悬浮按钮位置
    loadFloatingBtnPosition() {
      const savedPosition = localStorage.getItem('floatingBtnPosition')
      if (savedPosition) {
        this.floatingBtnPosition = JSON.parse(savedPosition)
      }
    },
    
    // 保存悬浮按钮位置
    saveFloatingBtnPosition() {
      localStorage.setItem('floatingBtnPosition', JSON.stringify(this.floatingBtnPosition))
    },
    
    // 处理按钮点击
    handleButtonClick(event) {
      // 如果正在拖拽，不触发点击事件
      if (this.isDragging || this.isTouchMoving) {
        return
      }
      this.openAddForm()
    },
    
    // 处理触摸开始
    handleTouchStart(event) {
      event.preventDefault()
      event.stopPropagation()
      
      this.touchStartTime = Date.now()
      this.isTouchMoving = false
      
      // 设置定时器，如果长按超过 200ms 则开始拖拽
      this.touchTimer = setTimeout(() => {
        this.startDrag(event)
        this.isTouchMoving = true
      }, 200)
    },
    
    // 处理触摸结束
    handleTouchEnd(event) {
      // 清除定时器
      if (this.touchTimer) {
        clearTimeout(this.touchTimer)
        this.touchTimer = null
      }
      
      // 如果不是拖拽状态且触摸时间短，则触发点击
      const touchDuration = Date.now() - this.touchStartTime
      if (!this.isDragging && !this.isTouchMoving && touchDuration < 200) {
        this.openAddForm()
      }
      
      this.stopDrag()
    },
    
    // 开始拖拽
    startDrag(event) {
      this.isDragging = true
      
      // 获取按钮的当前位置
      const buttonRect = event.target.getBoundingClientRect()
      
      // 计算鼠标/触摸点相对于按钮左上角的偏移量
      const clientX = event.type === 'mousedown' ? event.clientX : event.touches[0].clientX
      const clientY = event.type === 'mousedown' ? event.clientY : event.touches[0].clientY
      
      this.dragOffset = {
        x: clientX - buttonRect.left,
        y: clientY - buttonRect.top
      }
      
      // 添加事件监听器
      if (event.type === 'mousedown') {
        document.addEventListener('mousemove', this.onDrag)
        document.addEventListener('mouseup', this.stopDrag)
      } else {
        document.addEventListener('touchmove', this.onDrag, { passive: false })
        document.addEventListener('touchend', this.stopDrag)
      }
    },
    
    // 拖拽中
    onDrag(event) {
      if (!this.isDragging) return
      
      event.preventDefault()
      event.stopPropagation()
      
      const clientX = event.type === 'mousemove' ? event.clientX : event.touches[0].clientX
      const clientY = event.type === 'mousemove' ? event.clientY : event.touches[0].clientY
      
      // 计算按钮的新位置（基于鼠标位置和偏移量）
      const buttonWidth = 60 // 按钮宽度
      const buttonHeight = 60 // 按钮高度
      
      // 计算按钮的右下角坐标
      const newRight = window.innerWidth - (clientX - this.dragOffset.x + buttonWidth)
      const newBottom = window.innerHeight - (clientY - this.dragOffset.y + buttonHeight)
      
      // 限制在可视区域内
      const maxRight = window.innerWidth - buttonWidth - 10
      const maxBottom = window.innerHeight - buttonHeight - 10
      
      this.floatingBtnPosition.x = Math.max(10, Math.min(newRight, maxRight))
      this.floatingBtnPosition.y = Math.max(10, Math.min(newBottom, maxBottom))
    },
    
    // 停止拖拽
    stopDrag() {
      this.isDragging = false
      this.isTouchMoving = false
      
      // 移除事件监听器
      document.removeEventListener('mousemove', this.onDrag)
      document.removeEventListener('mouseup', this.stopDrag)
      document.removeEventListener('touchmove', this.onDrag)
      document.removeEventListener('touchend', this.stopDrag)
      
      // 保存位置
      this.saveFloatingBtnPosition()
    },
    
    async queryVirtualPlayList() {
      this.loading = true
      try {
        const res = await apiService.getFresh('/VirtualPlayQuery')
        this.virtualPlayList = res.data.virtualPlayList
      } catch (error) {
        console.error('获取虚拟歌单失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    async toggleStatus(item) {
      // 切换状态：true -> false, false -> true
      const newStatus = !item.status
      
      try {
        // 调用更新状态接口
        await this.virtualPlayStatusUpdate(item.id, newStatus)
        
        // 更新本地数据
        item.status = newStatus
      } catch (error) {
        console.error('更新状态失败:', error)
      }
    },
    
    async virtualPlayStatusUpdate(virtualId, status) {
      const headers = {token: `${tools.getTokenFromCookie()}`}
      const { res, isAuthenticated } = await tools.authApiCall(
        () => apiService.post('/VirtualPlayStatusUpdate',
          {virtual: virtualId, status: status}, { headers }),
        this.$router,
        this.$route
      )
    },
    
    openActionMenu(item, event) {
      this.currentItem = item
      this.showActionMenu = true
      
      // 计算菜单位置
      const rect = event.target.getBoundingClientRect()
      this.menuStyle = {
        top: `${rect.bottom + 5}px`,
        right: `${window.innerWidth - rect.right}px`
      }
    },
    
    closeActionMenu() {
      this.showActionMenu = false
      this.currentItem = null
    },
    
    openEditForm(item) {
      this.closeActionMenu()
      this.editForm = {
        id: item.id,
        name: item.name,
        left: item.left,
        opr: item.opr,
        right: item.right
      }
      this.showEditForm = true
    },
    
    closeEditForm() {
      this.showEditForm = false
      this.editForm = {
        id: '',
        name: '',
        left: '',
        opr: 'and',
        right: ''
      }
    },
    
    confirmDelete(item) {
      this.closeActionMenu()
      this.currentItem = item
      this.showDeleteConfirm = true
    },
    
    closeDeleteConfirm() {
      this.showDeleteConfirm = false
      this.currentItem = null
    },
    
    async deleteVirtualPlay() {
      if (!this.currentItem) return
      
      try {
        const headers = {token: `${tools.getTokenFromCookie()}`}
        // 调用删除接口
        await tools.authApiCall(
          () => apiService.post('/VirtualPlayRemove',
            { play: this.currentItem.id }, { headers }),
          this.$router,
          this.$route
        )
        
        // 从本地数据中移除
        this.virtualPlayList = this.virtualPlayList.filter(item => item.id !== this.currentItem.id)
        
        this.closeDeleteConfirm()
      } catch (error) {
        console.error('删除虚拟歌单失败:', error)
        alert('删除失败，请重试')
      }
    },
    
    async confirmEdit() {
      if (!this.validateForm(this.editForm)) {
        return
      }
      
      try {
        // 调用更新接口
        await this.virtualPlayUpdate(this.editForm)
        
        // 更新本地数据
        const index = this.virtualPlayList.findIndex(item => item.id === this.editForm.id)
        if (index !== -1) {
          this.virtualPlayList[index] = {
            ...this.virtualPlayList[index],
            ...this.editForm
          }
        }
        
        this.closeEditForm()
      } catch (error) {
        console.error('更新虚拟歌单失败:', error)
      }
    },
    
    openAddForm() {
      this.showAddForm = true
    },
    
    closeAddForm() {
      this.showAddForm = false
      this.addForm = {
        name: '',
        left: '',
        opr: 'and',
        right: ''
      }
    },
    
    async confirmAdd() {
      if (!this.validateForm(this.addForm)) {
        return
      }
      
      try {
        // 调用新增接口
        await this.virtualPlayUpdate(this.addForm)
        
        // 重新加载数据
        await this.queryVirtualPlayList()
        
        this.closeAddForm()
      } catch (error) {
        console.error('新增虚拟歌单失败:', error)
      }
    },
    
    async virtualPlayUpdate(formData) {
      const headers = {token: `${tools.getTokenFromCookie()}`}
      await tools.authApiCall(
        () => apiService.post('/VirtualPlayUpdate', {
          virtual: formData.id || "",
          name: formData.name,
          left: formData.left,
          opr: formData.opr,
          right: formData.right
      }, { headers }),
        this.$router,
        this.$route
      )
    },
    
    validateForm(form) {
      if (!form.left.trim()) {
        alert('请输入左值')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
.virtual-play-page {
  min-height: 100vh;
  background: #f8f9fa;
  position: relative;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  color: white;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: background 0.3s ease;
  flex-shrink: 0;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.header h1 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  text-align: center;
  flex: 1;
}

.content {
  padding: 20px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e0e0e0;
  border-top: 3px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.playlist-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.playlist-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.item-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.checkbox {
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.checkbox.checked {
  background: #667eea;
  border-color: #667eea;
}

.checkmark {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.item-condition {
  font-size: 14px;
  color: #666;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
}

.item-actions {
  display: flex;
  align-items: center;
}

.more-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background 0.3s ease;
}

.more-btn:hover {
  background: #f0f0f0;
}

/* 操作菜单样式 */
.action-menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 999;
}

.action-menu {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
  min-width: 120px;
  z-index: 1000;
  overflow: hidden;
}

.action-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 12px 16px;
  border: none;
  background: none;
  cursor: pointer;
  transition: background 0.3s ease;
  font-size: 14px;
  color: #333;
}

.action-menu-item:hover {
  background: #f5f5f5;
}

.action-menu-item.delete {
  color: #e74c3c;
}

.action-menu-item.delete:hover {
  background: #fee;
}

.action-icon {
  font-size: 16px;
}

/* 删除确认对话框 */
.confirm-modal {
  max-width: 300px;
}

.confirm-content {
  padding: 20px;
  text-align: center;
}

.confirm-content p {
  margin: 0;
  color: #333;
  font-size: 16px;
  line-height: 1.5;
}

.btn-danger {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(231, 76, 60, 0.3);
}

.btn-danger:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 16px;
  width: 100%;
  max-width: 400px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.close-btn:hover {
  background: #f0f0f0;
}

.form {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-input,
.form-select {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.btn {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.btn-cancel:hover {
  background: #e9ecef;
}

.btn-confirm {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.btn-confirm:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 悬浮添加按钮 */
.floating-add-btn {
  position: fixed;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 24px;
  cursor: grab;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 100;
  user-select: none;
  -webkit-user-select: none;
  touch-action: none;
}

.floating-add-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(102, 126, 234, 0.5);
}

.floating-add-btn:active {
  cursor: grabbing;
}
</style>
